package ontology;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class OntologyReader {
	
	private final SAXBuilder sb;
	private Document inputXML = null;
	private final Element rootElement;
	private final File ontologyFile;
	
	public OntologyReader(File f){
		this.ontologyFile = f;
		sb = new SAXBuilder();

		try {
			inputXML = sb.build(ontologyFile.toURL());
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		rootElement = inputXML.getRootElement();
	}
	
	public Element getElement(String id) {
		if(rootElement.getAttributeValue("id") != null){
			if(rootElement.getAttributeValue("id").equalsIgnoreCase(id)){
				return rootElement;
			}
		}
		Element e = getElement(rootElement, id);
		if(e == null){
			System.out.println("no such element exists: "+id+"\n");
			return null;
		} else {
			return e;
		}		
	}
	
	public Element getElement(Element ancestor, String id){
		Iterator<Element> children = ancestor.getChildren().iterator();
		while(children.hasNext()){
			Element child = children.next();
			if(isSameElem(child, id)){
				return child;
			} else {
				Element grandChild = getElement(child, id);
				if(grandChild != null){
					return grandChild;
				}
			}
				
		}
		return null;
	}
	
	private boolean isSameElem(Element e, String id){
		if(e.getAttributeValue("id") != null){
			if(e.getAttributeValue("id").equalsIgnoreCase(id)){
				return true;
			}
		}
		return false;
	}
	

}
